<template>
  <NuxtLayout>
    <div class="page-container mx-auto mt-[78px] overflow-x-hidden md:max-w-6xl">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
          <a href="/admin/article">文章列表</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>新增</el-breadcrumb-item>
      </el-breadcrumb>

      <h1 class="border-b border-gray-500 pb-4 pt-6 text-2xl text-white">新增文章</h1>

      <div class="text-md mt-6 flex flex-col gap-y-8 bg-white p-8">
        <el-form ref="formRef" label-width="100px" :rules="rules" :model="formModel">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formModel.title" maxlength="200"></el-input>
          </el-form-item>

          <el-form-item label="标题类型" prop="titleType">
            <el-radio-group v-model="formModel.titleType">
              <el-radio :value="1">文章id</el-radio>
              <el-radio :value="2">文章标题</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="文章摘要" prop="summary">
            <el-input type="textarea" :rows="4" show-word-limit v-model="formModel.summary" maxlength="200"></el-input>
          </el-form-item>
          <div class="pb-4 pl-[100px] text-sm text-red-400">
            文章摘要：如果开启了摘要功能，先取摘要，如果没有摘要，再取正文前200个字符
          </div>
          <el-form-item label="是否开启摘要" prop="openSummary">
            <el-radio-group v-model="formModel.openSummary">
              <el-radio :value="0">关闭</el-radio>
              <el-radio :value="1">开启</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="文章封面" prop="cover">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :http-request="onHandleUpload"
              :on-remove="handleRemove"
            >
              <img v-if="formModel.cover" :src="formModel.cover" />
              <el-icon v-else class="avatar-uploader-icon"><ElIconPlus /></el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="标签" prop="tags">
            <el-select multiple v-model="formModel.tags">
              <el-option
                v-for="(item, index) in tagList"
                :key="index"
                :value="item.tag_id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="文章关键字" prop="keyword">
            <el-input v-model="formModel.keyword" maxlength="1000"></el-input>
          </el-form-item>

          <div class="pb-4 pl-[100px] text-sm text-red-400">
            keyword 是搜索引擎的一部分，用于 SEO 优化，多个关键字用英文逗号隔开
          </div>
          <el-form-item label="描述" prop="description">
            <el-input v-model="formModel.description" maxlength="1000"></el-input>
          </el-form-item>
          <div class="pb-4 pl-[100px] text-sm text-red-400">
            description 是搜索引擎的一部分，用于 SEO 优化，描述内容[建议]不超过200个字符
          </div>

          <el-form-item label="正文" prop="content">
            <div class="eidtor-container flex w-full flex-col">
              <tinymce-editor style="height: 600px" v-model="formModel.content"></tinymce-editor>
            </div>
          </el-form-item>

          <!-- 富文本的内容 -->
          <div>
            <code>{{ formModel.content }}</code>
          </div>
        </el-form>
        <div class="flex w-full items-center justify-center">
          <div class="cursor-pointer rounded-md border border-gray-500 px-6 py-2" @click="onSubmit">提交</div>
        </div>
      </div>
    </div>
  </NuxtLayout>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'

const formModel = ref({
  content: '',
  title: '',
  summary: '',
  titleType: 2,

  openSummary: 1,

  // seo相关的
  keyword: '',
  description: '',
  // 封面图
  cover: '',
  tags: []
})

const formRef = ref<FormInstance>()

const rules = ref({
  title: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
  content: [{ required: true, message: '请输入内容', trigger: ['blur', 'change'] }]
})

const tagList = ref<any>([])

let { data, refresh, error } = await useFetch('/api/tag/queryAllTag')

if (data.value) {
  tagList.value = data.value.data || []
}

const handleRemove = () => {}

const onHandleUpload = async (options) => {
  let formData = new FormData()
  formData.append('file', options.file)

  let res = await $fetch('/api/upload', {
    method: 'POST',
    body: formData
  })

  options.onSuccess(res.data[0].url, options.file)

  formModel.value.cover = res.data[0].url
}

const onCheck = async () => {
  let isOk = true
  await formRef.value?.validate((valid) => {
    isOk = valid
  })

  console.log('验证结果', isOk)

  return isOk
}
const onSubmit = async () => {
  if (!(await onCheck())) return

  let saveRes = await $fetch('/api/articles/create', {
    method: 'POST',
    body: {
      ...formModel.value
    }
  })

  if (saveRes && saveRes.code === 0) {
    formRef.value!.resetFields()
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader :deep(.el-upload) {
  width: 178px;
  height: 178px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.eidtor-container {
  > div {
    flex: 1;
  }

  .tiptap {
    height: 100%;
  }
}
</style>
